<template>
  <div class="wrap">
    <div class="search-wrap">
      <el-input
        v-model.trim="search.rolename"
        @keyup.enter="getRoleList"
        placeholder="模糊搜索角色名"
        style="width: 350px"
      />
      <el-button class="search-class" type="primary" @click.stop="getRoleList"
        >查询</el-button
      >
    </div>
    <div class="table-header">
      <div>角色管理</div>
      <el-button class="add" type="primary" @click="addRow">新增</el-button>
    </div>
    <el-table :data="roleList" style="width: 100%">
      <!-- <el-table-column prop="id" label="id"> </el-table-column> -->
      <el-table-column prop="rolename" label="角色名称"> </el-table-column>
      <el-table-column prop="created_at" label="创建时间"> </el-table-column>
      <el-table-column prop="updated_at" label="更新时间"> </el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template v-slot="scope">
          <el-button
            size="small"
            type="primary"
            @click.stop="editorAccess(scope.row)"
          >
            添加权限
          </el-button>
          <el-button
            size="small"
            type="primary"
            @click.stop="editorRow(scope.row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            title="确认要删除该列?"
            confirm-button-text="是"
            cancel-button-text="否"
            @confirm="deleteRow(scope.row)"
          >
            <template #reference>
              <el-button> 删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-footer">
      <el-pagination
        background
        @current-change="currentChange"
        :page-size="pagination.pageSize"
        layout="prev, pager, next"
        :total="pagination.total"
      />
    </div>
    <!-- 角色管理 -->
    <el-dialog
      v-model="dialogRoleVisible"
      :close-on-click-modal="false"
      :title="dialogRoleTripType == 1 ? '新增' : '编辑'"
    >
      <el-form :model="form" label-position="top">
        <el-form-item label="角色名称" label-width="140px">
          <el-input v-model.number.trim="form.rolename"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogRoleVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加权限 -->
    <el-dialog
      v-model="dialogAddAccessVisible"
      :close-on-click-modal="false"
      title="设置权限"
      destroy-on-close
    >
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        auto-expand-parent
        highlight-current
        :expand-on-click-node="false"
        show-checkbox
        :checkStrictly="checkStrictly"
        @check-change="handleCheckChange"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogAddAccessVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddAccess"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from "utils/request";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "JddChromePluginsroleList",

  data() {
    return {
      dialogRoleVisible: false,
      dialogRoleTripType: 1, //1 新增 0 编辑
      dialogAddAccessVisible: false,
      search: {
        rolename: "",
      },
      pagination: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
      },
      form: {
        id: "",
        rolename: "",
      },
      formAccess: {
        id: "",
        accessIds: [],
      },
      roleList: [],
      allRoleList: [],
      defaultProps: {
        children: "children",
        label: "module_name",
      },
      checkStrictly: false,
      treeData: [],
    };
  },

  async mounted() {
    await this.getRoleList();
    await this.getAccessList();
  },
  watch: {
    dialogRoleVisible: {
      handler(value) {
        if (!value) {
          Object.assign(this.form, {
            id: "",
            rolename: "",
          });
        }
      },
    },
    dialogAddAccessVisible: {
      handler(value) {
        if (!value) {
          Object.assign(this.formAccess, {
            id: "",
            accessIds: [],
          });
        }
      },
    },
  },
  methods: {
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    async getAccessList() {
      let ret = await request.get("/access/list", {
        parentId: this.form.parentId,
      });
      if (ret.code == 200) {
        this.treeData = ret.data || [];
      }
    },
    async getRoleList() {
      let ret = await request.get("/role/list", {
        rolename: this.search.rolename,
        currentPage: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
      });
      if (ret.code == 200) {
        this.roleList = ret.data[0] || [];
        this.pagination.total = ret.data[1];
      }
    },
    async findUserSelfRoles(userId) {
      let ret = await request.get("/findUserSelfRoles", { userId });
      if (ret.code == 200) {
        this.form.roles = ret.data || [];
      }
    },
    async confirmAddRole() {
      let ret = {};
      if (this.dialogRoleTripType == 1) {
        ret = await request.post("/role/add", {
          rolename: this.form.rolename,
        });
      } else {
        ret = await request.patch(`/role/${this.form.id}`, {
          rolename: this.form.rolename,
        });
      }

      if (ret.code == 200) {
        this.$message({
          message: this.dialogRoleTripType == 1 ? "新增成功" : "编辑成功",
          type: "success",
        });
        this.getRoleList();
        this.dialogRoleVisible = false;
      } else {
        this.$message({
          message: ret.message,
          type: "error",
        });
      }
    },
    addRow() {
      this.dialogRoleTripType = 1;
      this.dialogRoleVisible = true;
    },
    editorRow(row) {
      this.dialogRoleTripType = 0;
      this.dialogRoleVisible = true;
      this.form.id = row.id;
      this.form.rolename = row.rolename;
    },
    async deleteRow(row) {
      let ret = await request.delete(`/role/${row.id}`, {});
      if (ret.code == 200) {
        ElMessage.success("删除成功");
        this.getRoleList();
      }
    },
    async currentChange(pageSize) {
      this.pagination.currentPage = pageSize;
      this.getRoleList();
    },
    async editorAccess(row) {
      await this.findRoleSelfAccess(row.id)
      this.formAccess.id = row.id;
      this.dialogAddAccessVisible = true;
      this.checkStrictly = true;
      this.$nextTick(() => {
        this.$refs['treeRef'].setCheckedKeys(this.form.accessIds,true);
        this.checkStrictly = false;
      });
    },
    async findRoleSelfAccess(roleId) {
      let ret = await request.get(`/role/hasaccess/${roleId}`);
      if (ret.code == 200) {
        this.form.accessIds = ret.data.map((item) => item.id) || [];
      }
    },
    async confirmAddAccess() {
      // getCheckedKeys 若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组。
      // (leafOnly) 接收一个 boolean 类型的参数，若为 true 则仅返回被选中的叶子节点的 keys，默认值为 false
      var checkedNodes = this.$refs["treeRef"].getCheckedNodes(false, true);
      var accessIds = [];
      checkedNodes.forEach((nodes) => {
        accessIds.push(nodes.id);
      });
      // 利用set没有重复的值这一特性, 实现数组去重。Array.form方法可以将 Set 结构转为数组。
      this.formAccess.accessIds = Array.from(new Set(accessIds));
      let ret = await request.post("/role/add/access", {
        roleId: this.formAccess.id,
        accessIds: this.formAccess.accessIds,
      });
      if (ret.code == 200) {
        this.$message({
          message: "修改成功",
          type: "success",
        });
        this.getRoleList();
        this.dialogAddAccessVisible = false;
      } else {
        this.$message({
          message: ret.message,
          type: "error",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.wrap {
  .headPictureCol {
    width: 32px;
    height: 32px;
    overflow: hidden;
    border-radius: 50%;
  }
  .search-wrap {
    display: flex;
    margin-bottom: 15px;
    .search-class {
      margin-left: 20px;
    }
  }
  .table-header {
    display: flex;
    line-height: 50px;
    padding: 0 10px;
    justify-content: space-between;
    align-items: center;
  }
  .pagination-footer {
    padding: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
